package com.ruoyi.project.service.impl;

import java.util.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanValidators;
//import com.sun.org.apache.regexp.internal.RE;
import org.springframework.data.redis.core.RedisTemplate;
import com.ruoyi.common.datascope.annotation.DataScope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.mapper.YhAppointmentMapper;
import com.ruoyi.project.domain.YhAppointment;
import com.ruoyi.project.service.IYhAppointmentService;

import javax.validation.Validator;

/**
 * 预约信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-03-09
 */
@Service
public class YhAppointmentServiceImpl implements IYhAppointmentService 
{
    @Autowired
    private YhAppointmentMapper yhAppointmentMapper;

    @Autowired
    protected Validator validator;
    @Autowired
    private RedisTemplate redisTemplate;

    private Date start;
    // 预约结束时间
    private Date end;
    /**
     * 导入设备数据
     *
     * @param mapList 设备数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importContract(List<YhAppointment> mapList, Boolean isUpdateSupport)
    {

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (YhAppointment map  : mapList) {
            try {
                YhAppointment c = yhAppointmentMapper.selectYhAppointmentById(map.getId());
                if (StringUtils.isNull(c)) {
                    BeanValidators.validateWithException(validator, map);
                    this.insertYhAppointment(map);
                    successNum++;
                    successMsg.append("<br/>" + successNum + " 导入成功");

                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, map);
                    successNum++;
                    successMsg.append("<br/>" + successNum + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }



    /**
     * 查询预约信息
     * 
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public YhAppointment selectYhAppointmentById(Long id)
    {
        return yhAppointmentMapper.selectYhAppointmentById(id);
    }

    /**
     * 查询预约信息列表
     * 
     * @param yhAppointment 预约信息
     * @return 预约信息
     */
    @Override
    @DataScope(deptAlias = "yh_appointment", userAlias = "yh_appointment")
    public List<YhAppointment> selectYhAppointmentList(YhAppointment yhAppointment)
    {
        return yhAppointmentMapper.selectYhAppointmentList(yhAppointment);
    }

    /**
     * 新增预约信息
     * 
     * @param yhAppointment 预约信息
     * @return 结果
     */
    @Override
    public int insertYhAppointment(YhAppointment yhAppointment)
    {
        yhAppointment.setCreateTime(DateUtils.getNowDate());
        return yhAppointmentMapper.insertYhAppointment(yhAppointment);
    }

    /**
     * 修改预约信息
     * 
     * @param yhAppointment 预约信息
     * @return 结果
     */
    @Override
    public int updateYhAppointment(YhAppointment yhAppointment)
    {
        yhAppointment.setUpdateTime(DateUtils.getNowDate());
        return yhAppointmentMapper.updateYhAppointment(yhAppointment);
    }

    /**
     * 批量删除预约信息
     * 
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteYhAppointmentByIds(Long[] ids)
    {
        return yhAppointmentMapper.deleteYhAppointmentByIds(ids);
    }

    /**
     * 删除预约信息信息
     * 
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteYhAppointmentById(Long id)
    {
        return yhAppointmentMapper.deleteYhAppointmentById(id);
    }

    @Override
    public int selectThing(YhAppointment yhAppointment) {
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = yhAppointment.getAppointmentStart().toInstant();
        Instant instant1 = yhAppointment.getAppointmentEnd().toInstant();
        LocalDateTime localDateTime1 = instant.atZone(zoneId).toLocalDateTime();
        LocalDateTime localDateTime2 = instant1.atZone(zoneId).toLocalDateTime();
        long startTimestamp = localDateTime1.toEpochSecond(ZoneOffset.UTC);
        long endTimestamp = localDateTime2.toEpochSecond(ZoneOffset.UTC);
        String appointment = yhAppointment.getId() + ":" + startTimestamp + ":" + endTimestamp;
        /*redisTemplate.opsForZSet().add("appointments" + yhAppointment.getInstrumentId(), appointment, startTimestamp);*/

//        if (getConflictingAppointments(startTimestamp, endTimestamp, yhAppointment).size() > 1) {
//            throw new ServiceException("该时间段已被预约");
//        }
        if (test(startTimestamp, endTimestamp, yhAppointment).size()>0) {
            throw new ServiceException("该时间段已被预约");
        }
        else {
            return 1;
        }

    }

    /*public List<String> getConflictingAppointments(Long  startTime, Long endTime, YhAppointment yhAppointment) {
        Set<String> appointments = redisTemplate.opsForZSet().rangeByScore("appointments" + yhAppointment.getInstrumentId(), startTime, endTime-1);
        List<String>  result=  appointments.stream()
                .map(appointment -> appointment.split(":")[0])
                .collect(Collectors.toList());
        return  result;


    }*/

    public  List<YhAppointment> test(Long  startTime, Long endTime, YhAppointment yhAppointment){

        List<YhAppointment> result = new ArrayList<>();
        List<YhAppointment> appointments =   yhAppointmentMapper.selectYhAppointmentByName(yhAppointment.getInstrumentId());
        for (YhAppointment appointment : appointments) {
            ZoneId zoneId = ZoneId.systemDefault();
            Instant instant = appointment.getAppointmentStart().toInstant();
            Instant instant1 = appointment.getAppointmentEnd().toInstant();
            LocalDateTime localDateTime1 = instant.atZone(zoneId).toLocalDateTime();
            LocalDateTime localDateTime2 = instant1.atZone(zoneId).toLocalDateTime();
            long startTimestamp = localDateTime1.toEpochSecond(ZoneOffset.UTC);
            long endTimestamp = localDateTime2.toEpochSecond(ZoneOffset.UTC);
            if (startTimestamp <= startTime && endTimestamp >= endTime) {
                result.add(appointment);
            }
            if (startTimestamp < endTime && endTimestamp > startTime) {
                result.add(appointment);
            }

        }

        return result;
    }

}
